﻿using HT.Framework;
using UnityEngine;
using UnityEngine.UI;

namespace TG
{
    public class TGDXLoadingPanel : HTBehaviour
    {
        public Image image;

        float realValue;
        float changeTime;
        float changeSpeed = 1;

        float tempTime;

        protected override void Awake()
        {
            base.Awake();
            AddEvent();

        }

        void AddEvent()
        {
            Main.m_Event.Subscribe<LoadingProgressChange>(SetProgress);
        }

        /// <summary>
        /// 设置进度
        /// </summary>
        /// <param name="progress"></param>
        public void SetProgress(EventHandlerBase eventHandler)
        {
            var args = eventHandler as LoadingProgressChange;
            if (args == null)
            {
                Debug.LogError($"参数错误！");
                return;
            }

            bool isClose = args.isClose;
            if (isClose)
            {
                gameObject.SetActive(false);
                return;
            }

            realValue = args.progress;
            changeTime = args.time;
            changeSpeed = realValue / changeTime;
            tempTime = 0f;
        }

        public void Update()
        {
            if (image.fillAmount >= 1)
                return;

            if (tempTime > changeTime)
            {
                image.fillAmount = realValue;
            }
            else
            {
                tempTime += Time.unscaledDeltaTime;
                if (image.fillAmount < realValue)
                    image.fillAmount += changeSpeed * Time.unscaledDeltaTime;
            }
        }

        void RemoveEvent()
        {
            Main.m_Event.Unsubscribe<LoadingProgressChange>(SetProgress);
        }

        protected override void OnDestroy()
        {
            RemoveEvent();
            base.OnDestroy();
        }
    }
}